// created by noellynch
// Apr 25, 2008

package com.sceneworker.util.xml;

import java.lang.reflect.Constructor;
import java.util.Hashtable;
import java.util.Stack;

import org.xml.sax.Attributes;

public class TagCallBackLoader extends GenericXMLLoader {

	private		Hashtable<String, TagCallbackStruct>		mcla_callbacks = new Hashtable<String, TagCallbackStruct>();
	private		Stack<Object>								mcl_dataSinkStack = new Stack<Object>();
	
	public 	TagCallBackLoader(Object cl_dataSink) {
		mcl_dataSinkStack.push(cl_dataSink);
	}
	
	public	Object
	getCurrentDataSink() {
		return mcl_dataSinkStack.peek();
	}
	
	public	void
	pushDataSink(Object cl_dataSink) {
		mcl_dataSinkStack.push(cl_dataSink);
	}
	
	public	void
	popDataSink() {
		mcl_dataSinkStack.pop();
	}
	
	public	void
	addCallback(String str_tag, TagCallbackStruct cl_listener) {
		
		mcla_callbacks.put(str_tag, cl_listener);
	}
	
	@Override
	public void 
	handleEndTag(String str_tag, String str_tagData) 
	{
		TagCallbackStruct		lcl_callback = mcla_callbacks.get(str_tag);
		
		if(lcl_callback == null)
		{
			return;
		}
		
		lcl_callback.getCurrentCallbackSink().handleEnd(this, str_tagData);
	}

	@Override
	public void 
	handleStartTag(String str_tag, Attributes cl_attrs) 
	{
		TagCallbackStruct		lcl_callback = mcla_callbacks.get(str_tag);
		
		if(lcl_callback == null)
		{
			return;
		}
		
		//ThruuGlobals.logInfo(this, "handleStartTag", "starting call back for  = " + str_tag);
		
		// create the class from the name provided
		try {
			
			Class<?>		lcl_class = Class.forName(lcl_callback.getClassName());
			lcl_callback.setCurrentCallbackSink((TagCallback)lcl_class.newInstance());
			
			Hashtable<String, String>		lcla_attrs = new Hashtable<String, String>();
			
			for(int li_index = 0; li_index < cl_attrs.getLength(); li_index++)
			{
				//ThruuGlobals.logInfo(this, "handleStartTag", "local name = " + cl_attrs.getQName(li_index));
				lcla_attrs.put(cl_attrs.getQName(li_index), cl_attrs.getValue(li_index));
			}
			
			lcl_callback.getCurrentCallbackSink().handleStart(this, lcla_attrs);
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
